import React, { useState, useEffect } from 'react';
import {
  Table,
  Button,
  Space,
  Modal,
  Form,
  Input,
  Select,
  Tree,
  Tag,
  Popconfirm,
  Card,
  Row,
  Col,
  Typography,
  Tooltip,
  Badge,
  InputNumber,
  Statistic,
  Drawer,
  Descriptions,
  message,
  Tabs,
  Divider,
  List,
  Alert,
} from 'antd';
import {
  PlusOutlined,
  EditOutlined,
  DeleteOutlined,
  ReloadOutlined,
  FileOutlined,
  ApiOutlined,
  MenuOutlined,
  ControlOutlined,
  ExpandOutlined,
  CompressOutlined,
  EyeOutlined,
  SafetyOutlined,
  SettingOutlined,
  FilterOutlined,
  BulbOutlined,
} from '@ant-design/icons';
import type { ColumnsType } from 'antd/es/table';
import {
  usePermissions,
  usePermissionActions,
  usePermissionStats,
  type PermissionFormData,
} from '@/hooks/business/usePermissions';
import type { Permission } from '@/types/rbac';

const { Option } = Select;
const { Title, Text } = Typography;
const { Search } = Input;
const { TextArea } = Input;

const Permissions: React.FC = () => {
  // 核心状态管理
  const [selectedKeys, setSelectedKeys] = useState<string[]>([]);
  const [expandedKeys, setExpandedKeys] = useState<string[]>([]);
  const [searchText, setSearchText] = useState('');
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [isViewDrawerVisible, setIsViewDrawerVisible] = useState(false);
  const [editingPermission, setEditingPermission] = useState<Permission | null>(null);
  const [viewingPermission, setViewingPermission] = useState<Permission | null>(null);
  const [autoExpandParent, setAutoExpandParent] = useState(true);
  const [typeFilter, setTypeFilter] = useState<string>('');
  const [permissionTree, setPermissionTree] = useState<any[]>([]);
  const [permissionTreeLoading, setPermissionTreeLoading] = useState(false);
  const [allPermissions, setAllPermissions] = useState<Permission[]>([]);
  const [allPermissionsLoading, setAllPermissionsLoading] = useState(false);
  const [treeCollapsed, setTreeCollapsed] = useState(false);
  // 权限条件相关状态
  const [conditionsVisible, setConditionsVisible] = useState(false);
  const [selectedPermissionForConditions, setSelectedPermissionForConditions] = useState<Permission | null>(null);
  const [permissionConditions, setPermissionConditions] = useState<any[]>([]);
  const [conditionForm] = Form.useForm();
  const [form] = Form.useForm();
  const [conditionModalVisible, setConditionModalVisible] = useState(false);
  const [editingCondition, setEditingCondition] = useState<any>(null);

  // 使用权限相关的hooks
  const { permissions, loading: permissionsLoading, total, loadPermissions } = usePermissions();
  const { 
    createPermission, 
    updatePermission, 
    deletePermission, 
    batchDeletePermissions,
    movePermission,
    batchUpdateSort,
    checkPermissionCode,
    loading: actionLoading 
  } = usePermissionActions();
  const { stats, loading: statsLoading } = usePermissionStats();

  // 加载权限树数据用于左侧树形显示
  const loadPermissionTree = async () => {
    try {
      setPermissionTreeLoading(true);
      const { permissionApi } = await import('@/services/cloud/api/permissionApi');
      const tree = await permissionApi.getPermissionTree();
      setPermissionTree(tree);
      // 默认展开第一层
      if (tree && tree.length > 0) {
        const firstLevelKeys = tree.map(item => item.id);
        setExpandedKeys(firstLevelKeys);
      }
    } catch (error) {
      console.error('获取权限树失败:', error);
      message.error('获取权限树失败');
    } finally {
      setPermissionTreeLoading(false);
    }
  };

  // 加载全部权限数据用于右侧表格显示
  const loadAllPermissions = async () => {
    try {
      setAllPermissionsLoading(true);
      const { permissionApi } = await import('@/services/cloud/api/permissionApi');
      const allPerms = await permissionApi.getAllPermissions();
      setAllPermissions(allPerms);
    } catch (error) {
      console.error('获取全部权限失败:', error);
      message.error('获取全部权限失败');
    } finally {
      setAllPermissionsLoading(false);
    }
  };

  // 初始化加载数据
  useEffect(() => {
    loadPermissionTree();
    loadAllPermissions();
  }, []);

  // 刷新数据
  const refresh = () => {
    loadPermissionTree();
    loadAllPermissions();
  };

  // 树操作函数  
  const expandAll = () => {
    const getAllKeys = (nodes: any[]): string[] => {
      let keys: string[] = [];
      nodes.forEach(node => {
        keys.push(node.key || node.id);
        if (node.children && node.children.length > 0) {
          keys = keys.concat(getAllKeys(node.children));
        }
      });
      return keys;
    };
    const allKeys = getAllKeys(permissionTree);
    setExpandedKeys(allKeys);
  };

  const collapseAll = () => {
    setExpandedKeys([]);
  };

  const onExpand = (expandedKeysValue: React.Key[]) => {
    setExpandedKeys(expandedKeysValue as string[]);
    setAutoExpandParent(false);
  };

  const onSelect = (selectedKeysValue: React.Key[]) => {
    setSelectedKeys(selectedKeysValue as string[]);
  };

  // 获取权限图标
  const getPermissionIcon = (type: string) => {
    switch (type) {
      case 'menu':
        return <MenuOutlined style={{ color: '#64748b' }} />;
      case 'button':
        return <ControlOutlined style={{ color: '#64748b' }} />;
      case 'api':
        return <ApiOutlined style={{ color: '#64748b' }} />;
      default:
        return <FileOutlined style={{ color: '#64748b' }} />;
    }
  };

  // 获取类型颜色和标签
  const getTypeColor = (type: string) => {
    switch (type) {
      case 'menu': return 'blue';
      case 'button': return 'geekblue';
      case 'api': return 'purple';
      default: return 'default';
    }
  };

  const getTypeLabel = (type: string) => {
    switch (type) {
      case 'menu': return '菜单';
      case 'button': return '按钮';
      case 'api': return 'API';
      default: return type;
    }
  };

  // 转换权限树数据为Tree组件需要的格式（修复递归显示children问题）
  const convertToTreeData = (permissions: any[]): any[] => {
    if (!permissions || permissions.length === 0) {
      return [];
    }
    
    return permissions.map(permission => {
      const treeNode = {
        key: permission.id,
        title: (
          <Space>
            {getPermissionIcon(permission.type)}
            <span>{permission.name || permission.code || '未命名权限'}</span>
          </Space>
        ),
        ...permission // 保留原始数据
      };
      
      // 递归处理children
      if (permission.children && permission.children.length > 0) {
        treeNode.children = convertToTreeData(permission.children);
      }
      
      return treeNode;
    });
  };

  // 根据选中的树节点过滤权限
  const getFilteredPermissions = () => {
    let filtered = allPermissions;

    // 根据选中的树节点过滤
    if (selectedKeys.length > 0) {
      const selectedNodeIds = new Set<string>();
      
      // 递归获取选中节点及其所有子节点
      const addNodeAndChildren = (nodeId: string) => {
        const node = allPermissions.find(p => p.id === nodeId);
        if (node) {
          selectedNodeIds.add(node.id);
          const children = allPermissions.filter(p => p.parentId === nodeId);
          children.forEach(child => addNodeAndChildren(child.id));
        }
      };

      selectedKeys.forEach(key => {
        addNodeAndChildren(key);
      });

      filtered = allPermissions.filter(permission => selectedNodeIds.has(permission.id));
    }

    // 根据搜索文本过滤
    if (searchText) {
      filtered = filtered.filter(permission =>
        permission.name.toLowerCase().includes(searchText.toLowerCase()) ||
        permission.code.toLowerCase().includes(searchText.toLowerCase()) ||
        (permission.description && permission.description.toLowerCase().includes(searchText.toLowerCase()))
      );
    }

    // 根据类型过滤
    if (typeFilter) {
      filtered = filtered.filter(permission => permission.type === typeFilter);
    }

    return filtered;
  };

  // 事件处理函数
  const handleAdd = (parentId?: string) => {
    setEditingPermission(null);
    setIsModalVisible(true);
    form.resetFields();
    if (parentId) {
      form.setFieldValue('parentId', parentId);
    }
  };

  const handleEdit = (permission: Permission) => {
    setEditingPermission(permission);
    setIsModalVisible(true);
    form.setFieldsValue(permission);
  };

  // 删除权限
  const handleDelete = async (permissionId: string) => {
    try {
      await deletePermission(permissionId);
      refresh();
    } catch (error) {
      // 错误已在hook中处理
    }
  };

  // 查看权限详情
  const handleView = (permission: any) => {
    setViewingPermission(permission);
    setIsViewDrawerVisible(true);
  };

  // 权限条件操作函数
  const handleManageConditions = (permission: Permission) => {
    setSelectedPermissionForConditions(permission);
    loadPermissionConditions(permission.id);
    setConditionsVisible(true);
  };

  // 加载权限条件
  const loadPermissionConditions = async (permissionId: string) => {
    try {
      const { permissionConditionApi } = await import('@/services/cloud/api/permissionConditionApi');
      const response = await permissionConditionApi.getByPermissionId(permissionId);
      setPermissionConditions(response.data || response || []);
    } catch (error) {
      console.error('加载权限条件失败:', error);
      message.error('加载权限条件失败');
    }
  };

  // 新增权限条件
  const handleAddCondition = () => {
    setEditingCondition(null);
    conditionForm.resetFields();
    if (selectedPermissionForConditions) {
      conditionForm.setFieldValue('permissionId', selectedPermissionForConditions.id);
    }
    setConditionModalVisible(true);
  };

  // 编辑权限条件
  const handleEditCondition = (condition: any) => {
    setEditingCondition(condition);
    conditionForm.setFieldsValue(condition);
    setConditionModalVisible(true);
  };

  // 提交权限条件
  const handleConditionSubmit = async (values: any) => {
    try {
      const { permissionConditionApi } = await import('@/services/cloud/api/permissionConditionApi');
      
      if (editingCondition) {
        await permissionConditionApi.update({ ...values, id: editingCondition.id });
        message.success('更新权限条件成功');
      } else {
        await permissionConditionApi.create(values);
        message.success('创建权限条件成功');
      }
      
      setConditionModalVisible(false);
      conditionForm.resetFields();
      if (selectedPermissionForConditions) {
        loadPermissionConditions(selectedPermissionForConditions.id);
      }
    } catch (error) {
      message.error(editingCondition ? '更新权限条件失败' : '创建权限条件失败');
    }
  };

  // 删除权限条件
  const handleDeleteCondition = async (conditionId: string) => {
    try {
      const { permissionConditionApi } = await import('@/services/cloud/api/permissionConditionApi');
      await permissionConditionApi.delete(conditionId);
      message.success('删除权限条件成功');
      if (selectedPermissionForConditions) {
        loadPermissionConditions(selectedPermissionForConditions.id);
      }
    } catch (error) {
      message.error('删除权限条件失败');
    }
  };

  const handleSubmit = async (values: PermissionFormData) => {
    try {
      if (editingPermission) {
        await updatePermission(editingPermission.id, values);
      } else {
        await createPermission(values);
      }
      
      setIsModalVisible(false);
      form.resetFields();
      refresh();
    } catch (error) {
      // 错误已在hook中处理
    }
  };

  const handleSearch = (value: string) => {
    setSearchText(value);
  };

  const handleTreeToggle = () => {
    if (treeCollapsed) {
      expandAll();
    } else {
      collapseAll();
    }
    setTreeCollapsed(!treeCollapsed);
  };

  const filteredPermissions = getFilteredPermissions();

  const columns: ColumnsType<Permission> = [
    {
      title: '权限信息',
      dataIndex: 'name',
      key: 'name',
      width: 250,
      render: (text, record) => (
        <Space>
          <div>
            <div style={{ fontWeight: 'bold' }}>{text}</div>
            <div style={{ fontSize: '12px', color: '#64748b' }}>
              代码: {record.code}
            </div>
          </div>
        </Space>
      ),
    },
    {
      title: '类型',
      dataIndex: 'type',
      key: 'type',
      width: 100,
      render: (type: string) => (
        <Tag color={getTypeColor(type)}>{getTypeLabel(type)}</Tag>
      ),
    },
    {
      title: '分类',
      dataIndex: 'category',
      key: 'category',
      width: 100,
      render: (category: string) => (
        category ? <Tag color="purple">{category}</Tag> : '-'
      ),
    },
    {
      title: '路径/方法',
      key: 'pathMethod',
      width: 200,
      render: (_, record) => (
        <div>
          {record.path && <div style={{ fontSize: '12px' }}>路径: {record.path}</div>}
          {record.method && <div>方法: <Tag color="geekblue">{record.method}</Tag></div>}
        </div>
      ),
    },
    {
      title: '资源/动作',
      key: 'resourceAction',
      width: 150,
      render: (_, record) => (
        <div>
          {record.resource && <div style={{ fontSize: '12px' }}>资源: {record.resource}</div>}
          {record.action && <div style={{ fontSize: '12px' }}>动作: {record.action}</div>}
          {record.scope && <div style={{ fontSize: '12px' }}>范围: {record.scope}</div>}
        </div>
      ),
    },
    {
      title: '描述',
      dataIndex: 'description',
      key: 'description',
      ellipsis: true,
    },
    {
      title: '排序',
      dataIndex: 'sort',
      key: 'sort',
      width: 80,
      sorter: (a, b) => (a.sort || 0) - (b.sort || 0),
    },
    {
      title: '操作',
      key: 'action',
      width: 150,
      fixed: 'right',
      render: (_, record) => (
        <Space size="small">
          <Tooltip title="查看">
            <Button
              type="link"
              size="small"
              icon={<EyeOutlined />}
              onClick={() => handleView(record)}
            />
          </Tooltip>
          <Tooltip title="条件管理">
            <Button
              type="link"
              size="small"
              icon={<BulbOutlined />}
              onClick={() => handleManageConditions(record)}
              style={{ color: '#722ed1' }}
            />
          </Tooltip>
          <Tooltip title="编辑">
            <Button
              type="link"
              size="small"
              icon={<EditOutlined />}
              onClick={() => handleEdit(record)}
            />
          </Tooltip>
          <Tooltip title="删除">
            <Popconfirm
              title="确定要删除这个权限吗？"
              description="删除后不可恢复，请谨慎操作"
              onConfirm={() => handleDelete(record.id)}
              okText="确定"
              cancelText="取消"
            >
              <Button
                type="link"
                size="small"
                icon={<DeleteOutlined />}
                danger
              />
            </Popconfirm>
          </Tooltip>
        </Space>
      ),
    },
  ];

  return (
    <div>
      {/* 页面标题 */}
      <div style={{ marginBottom: 16, display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
        <div>
          <Title level={4} style={{ margin: 0, display: 'flex', alignItems: 'center' }}>
            <SafetyOutlined style={{ marginRight: 8, color: '#1890ff' }} />
            权限管理
          </Title>
          <Text type="secondary">管理系统权限信息和层级结构</Text>
        </div>
        <Space>
          <Search
            placeholder="搜索权限名称、代码或描述"
            allowClear
            style={{ width: 300 }}
            onSearch={handleSearch}
          />
          <Button 
            icon={<ReloadOutlined />} 
            onClick={refresh} 
            loading={permissionsLoading}
          >
            刷新
          </Button>
          <Button 
            type="primary" 
            icon={<PlusOutlined />} 
            onClick={() => handleAdd()}
          >
            新增权限
          </Button>
        </Space>
      </div>

      <Row gutter={16}>
        {/* 权限树 */}
        <Col span={7}>
          <Card
            title={
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                <span>权限树</span>
                <Space>
                  <Button
                    type="text"
                    icon={treeCollapsed ? <ExpandOutlined /> : <CompressOutlined />}
                    onClick={handleTreeToggle}
                    size="small"
                  />
                  <Button
                    type="text"
                    icon={<ReloadOutlined />}
                    onClick={refresh}
                    size="small"
                  />
                </Space>
              </div>
            }
            style={{ height: 'calc(100vh - 300px)' }}
            bodyStyle={{ height: 'calc(100vh - 350px)', overflow: 'auto', padding: '16px' }}
          >
            {allPermissionsLoading ? (
              <div style={{ textAlign: 'center', padding: '20px' }}>
                加载中...
              </div>
            ) : (
              <Tree
                treeData={convertToTreeData(permissionTree)}
                selectedKeys={selectedKeys}
                expandedKeys={expandedKeys}
                autoExpandParent={autoExpandParent}
                onExpand={onExpand}
                onSelect={onSelect}
                style={{ 
                  fontSize: '15px',
                  height: '100%',
                  overflow: 'auto'
                }}
                height={window.innerHeight - 400}
                virtual
              />
            )}
          </Card>
        </Col>

        {/* 权限列表 */}
        <Col span={17}>
          <Card bodyStyle={{ padding: 2 }}>
            <div style={{ padding: '0 24px 24px 24px' }}>
              <Table
                columns={columns}
                dataSource={getFilteredPermissions()}
                rowKey="id"
                loading={allPermissionsLoading}
                pagination={false}
                scroll={{ x: 1200, y: 'calc(100vh - 400px)' }}
              />
            </div>
          </Card>
        </Col>
      </Row>

      {/* 权限表单模态框 */}
      <Modal
        title={editingPermission ? '编辑权限' : '新增权限'}
        open={isModalVisible}
        onCancel={() => {
          setIsModalVisible(false);
          form.resetFields();
        }}
        footer={null}
        width={900}
      >
        <Form
          form={form}
          layout="vertical"
          onFinish={handleSubmit}
        >
          <Row gutter={16}>
            <Col span={8}>
              <Form.Item
                name="name"
                label="权限名称"
                rules={[{ required: true, message: '请输入权限名称' }]}
                style={{ marginBottom: 16 }}
              >
                <Input placeholder="请输入权限名称" />
              </Form.Item>
            </Col>
            <Col span={8}>
              <Form.Item
                name="code"
                label="权限代码"
                rules={[{ required: true, message: '请输入权限代码' }]}
                style={{ marginBottom: 16 }}
              >
                <Input placeholder="请输入权限代码" />
              </Form.Item>
            </Col>
            <Col span={8}>
              <Form.Item
                name="type"
                label="权限类型"
                rules={[{ required: true, message: '请选择权限类型' }]}
                style={{ marginBottom: 16 }}
              >
                <Select placeholder="请选择权限类型">
                  <Option value={1}>目录</Option>
                  <Option value={2}>菜单</Option>
                  <Option value={3}>按钮</Option>
                </Select>
              </Form.Item>
            </Col>
          </Row>

          <Row gutter={16}>
            <Col span={8}>
              <Form.Item
                name="category"
                label="权限分类"
                rules={[{ required: true, message: '请选择权限分类' }]}
                style={{ marginBottom: 16 }}
              >
                <Select placeholder="请选择权限分类">
                  <Option value="system">系统管理</Option>
                  <Option value="user">用户管理</Option>
                  <Option value="role">角色管理</Option>
                  <Option value="permission">权限管理</Option>
                  <Option value="department">部门管理</Option>
                  <Option value="business">业务功能</Option>
                  <Option value="other">其他</Option>
                </Select>
              </Form.Item>
            </Col>
            <Col span={8}>
              <Form.Item
                name="parentId"
                label="父级权限"
                style={{ marginBottom: 16 }}
              >
                <Select placeholder="请选择父级权限" allowClear>
                  {permissions
                    .filter(p => p.type === 'menu' || p.type === 'button')
                    .map(permission => (
                      <Option key={permission.id} value={permission.id}>
                        {permission.name}
                      </Option>
                    ))}
                </Select>
              </Form.Item>
            </Col>
            <Col span={8}>
              <Form.Item
                name="status"
                label="状态"
                initialValue={1}
                rules={[{ required: true, message: '请选择状态' }]}
                style={{ marginBottom: 16 }}
              >
                <Select placeholder="请选择状态">
                  <Option value={1}>启用</Option>
                  <Option value={0}>禁用</Option>
                </Select>
              </Form.Item>
            </Col>
          </Row>

          <Form.Item
            noStyle
            shouldUpdate={(prevValues, currentValues) => prevValues.type !== currentValues.type}
          >
            {({ getFieldValue }) => {
              const type = getFieldValue('type');
              return (
                <>
                  {(type === 2 || type === 3) && (
                    <Row gutter={16}>
                      <Col span={24}>
                        <Form.Item
                          name="path"
                          label="菜单路径"
                          rules={type === 2 ? [{ required: true, message: '请输入菜单路径' }] : []}
                          style={{ marginBottom: 16 }}
                        >
                          <Input placeholder="请输入菜单路径" />
                        </Form.Item>
                      </Col>
                    </Row>
                  )}
                  
                  {type === 2 && (
                    <Row gutter={16}>
                      <Col span={12}>
                        <Form.Item
                          name="icon"
                          label="菜单图标"
                          style={{ marginBottom: 16 }}
                        >
                          <Input placeholder="请输入图标名称" />
                        </Form.Item>
                      </Col>
                      <Col span={12}>
                        <Form.Item
                          name="permissions"
                          label="权限标识"
                          style={{ marginBottom: 16 }}
                        >
                          <Input placeholder="请输入权限标识，多个用逗号分隔" />
                        </Form.Item>
                      </Col>
                    </Row>
                  )}
                  
                  {type === 3 && (
                    <Form.Item
                      name="permissions"
                      label="权限标识"
                      rules={[{ required: true, message: '请输入权限标识' }]}
                      style={{ marginBottom: 16 }}
                    >
                      <Input placeholder="请输入权限标识" />
                    </Form.Item>
                  )}
                </>
              );
            }}
          </Form.Item>

          <Row gutter={16}>
            <Col span={24}>
              <Form.Item
                name="sort"
                label="排序"
                initialValue={1}
                rules={[{ required: true, message: '请输入排序' }]}
                style={{ marginBottom: 16 }}
              >
                <InputNumber min={1} max={999} style={{ width: '100%' }} />
              </Form.Item>
            </Col>
          </Row>

          <Row gutter={16}>
            <Col span={8}>
              <Form.Item
                name="resource"
                label="资源"
                rules={[{ required: true, message: '请选择资源' }]}
                style={{ marginBottom: 16 }}
              >
                <Select placeholder="请选择资源" allowClear>
                  <Option value="user">用户</Option>
                  <Option value="role">角色</Option>
                  <Option value="menu">菜单</Option>
                  <Option value="tenant">租户</Option>
                  <Option value="dept">部门</Option>
                  <Option value="team">团队</Option>
                  <Option value="business">业务</Option>
                  <Option value="data">数据</Option>
                  <Option value="log">日志</Option>
                  <Option value="audit">审计</Option>
                  <Option value="system">系统</Option>
                </Select>
              </Form.Item>
            </Col>
            <Col span={8}>
              <Form.Item
                name="action"
                label="动作"
                rules={[{ required: true, message: '请选择动作' }]}
                style={{ marginBottom: 16 }}
              >
                <Select placeholder="请选择动作" allowClear>
                  <Option value="read">查看</Option>
                  <Option value="write">写入</Option>
                  <Option value="delete">删除</Option>
                  <Option value="manage">管理</Option>
                  <Option value="config">配置</Option>
                  <Option value="monitor">监控</Option>
                  <Option value="*">全部</Option>
                </Select>
              </Form.Item>
            </Col>
            <Col span={8}>
              <Form.Item
                name="scope"
                label="范围"
                rules={[{ required: true, message: '请选择范围' }]}
                style={{ marginBottom: 16 }}
              >
                <Select placeholder="请选择范围" allowClear>
                  <Option value="platform">平台级</Option>
                  <Option value="system">系统级</Option>
                  <Option value="tenant">租户级</Option>
                  <Option value="department">部门级</Option>
                  <Option value="team">团队级</Option>
                  <Option value="personal">个人级</Option>
                </Select>
              </Form.Item>
            </Col>
          </Row>

          <Form.Item
            name="description"
            label="权限描述"
            style={{ marginBottom: 16 }}
          >
            <TextArea rows={3} placeholder="请输入权限描述" />
          </Form.Item>

          <Form.Item style={{ marginBottom: 0, textAlign: 'right' }}>
            <Space>
              <Button onClick={() => {
                setIsModalVisible(false);
                form.resetFields();
              }}>
                取消
              </Button>
              <Button type="primary" htmlType="submit" loading={actionLoading}>
                {editingPermission ? '更新' : '创建'}
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </Modal>

      {/* 权限条件管理 Modal */}
      <Modal
        title={
          <Space>
            <BulbOutlined style={{ color: '#722ed1' }} />
            <span>权限条件管理 - {selectedPermissionForConditions?.name}</span>
          </Space>
        }
        open={conditionsVisible}
        onCancel={() => setConditionsVisible(false)}
        width={900}
        footer={[
          <Button key="close" onClick={() => setConditionsVisible(false)}>
            关闭
          </Button>
        ]}
      >
        <Alert
          message="权限条件说明"
          description="权限条件用于实现基于属性的访问控制（ABAC），可以根据用户属性、资源属性、环境属性等进行细粒度权限控制。"
          type="info"
          showIcon
          style={{ marginBottom: 16 }}
        />
        
        <div style={{ marginBottom: 16 }}>
          <Button 
            type="primary" 
            icon={<PlusOutlined />} 
            onClick={handleAddCondition}
          >
            新增条件
          </Button>
        </div>

        <List
          dataSource={permissionConditions}
          renderItem={(condition) => (
            <List.Item
              actions={[
                <Button 
                  type="link" 
                  icon={<EditOutlined />} 
                  size="small"
                  onClick={() => handleEditCondition(condition)}
                >
                  编辑
                </Button>,
                <Popconfirm
                  title="确定要删除这个条件吗？"
                  onConfirm={() => handleDeleteCondition(condition.id)}
                >
                  <Button 
                    type="link" 
                    icon={<DeleteOutlined />} 
                    size="small"
                    danger
                  >
                    删除
                  </Button>
                </Popconfirm>
              ]}
            >
              <List.Item.Meta
                title={
                  <Space>
                    <Tag color={condition.type === 'user' ? 'blue' : condition.type === 'resource' ? 'green' : 'orange'}>
                      {condition.type === 'user' ? '用户条件' : condition.type === 'resource' ? '资源条件' : '环境条件'}
                    </Tag>
                    <Text strong>{condition.field} {condition.operator} {condition.contextField || condition.value}</Text>
                  </Space>
                }
                description={
                  <div>
                    <Text type="secondary">{condition.description}</Text>
                    <br />
                    <Text type="secondary" style={{ fontSize: '12px' }}>
                      字段: {condition.field} | 操作符: {condition.operator} | 
                      {condition.contextField ? `上下文字段: ${condition.contextField}` : `值: ${condition.value}`}
                    </Text>
                  </div>
                }
              />
            </List.Item>
          )}
        />
      </Modal>

      {/* 查看权限详情侧边栏 */}
      <Drawer
        title="权限详情"
        placement="right"
        width={600}
        open={isViewDrawerVisible}
        onClose={() => setIsViewDrawerVisible(false)}
        extra={
          <Space>
            <Button 
              type="primary" 
              icon={<EditOutlined />}
              onClick={() => {
                if (viewingPermission) {
                  setIsViewDrawerVisible(false);
                  handleEdit(viewingPermission);
                }
              }}
            >
              编辑
            </Button>
          </Space>
        }
      >
        {viewingPermission && (
          <Descriptions column={1} bordered>
            <Descriptions.Item label="权限名称">
              <Space>
                {getPermissionIcon(viewingPermission.type || 'default')}
                <Text strong>{viewingPermission.name}</Text>
              </Space>
            </Descriptions.Item>
            
            <Descriptions.Item label="权限编码">
              <Text code>{viewingPermission.code}</Text>
            </Descriptions.Item>
            
            <Descriptions.Item label="权限类型">
              <Tag color={getTypeColor(viewingPermission.type || '')}>
                {getTypeLabel(viewingPermission.type || '')}
              </Tag>
            </Descriptions.Item>
            
            <Descriptions.Item label="描述">
              <Text>{viewingPermission.description || '暂无描述'}</Text>
            </Descriptions.Item>
            
            <Descriptions.Item label="排序">
              <Text>{viewingPermission.sort}</Text>
            </Descriptions.Item>
            
            <Descriptions.Item label="创建时间">
              <Text>{viewingPermission.createTime}</Text>
            </Descriptions.Item>
            
            <Descriptions.Item label="更新时间">
              <Text>{viewingPermission.updateTime}</Text>
            </Descriptions.Item>
          </Descriptions>
        )}
      </Drawer>

      {/* 权限条件编辑 Modal */}
      <Modal
        title={editingCondition ? '编辑权限条件' : '新增权限条件'}
        open={conditionModalVisible}
        onCancel={() => {
          setConditionModalVisible(false);
          conditionForm.resetFields();
          setEditingCondition(null);
        }}
        footer={null}
        width={700}
      >
        <Form
          form={conditionForm}
          layout="vertical"
          onFinish={handleConditionSubmit}
        >
          <Form.Item name="permissionId" hidden>
            <Input />
          </Form.Item>
          
          <Row gutter={16}>
            <Col span={8}>
              <Form.Item
                name="field"
                label="条件字段"
                rules={[{ required: true, message: '请输入条件字段' }]}
              >
                <Input placeholder="如: department, ownerId, status" />
              </Form.Item>
            </Col>
            <Col span={8}>
              <Form.Item
                name="operator"
                label="操作符"
                rules={[{ required: true, message: '请选择操作符' }]}
              >
                <Select placeholder="请选择操作符">
                  <Option value="=">等于 (=)</Option>
                  <Option value="!=">不等于 (!=)</Option>
                  <Option value="in">包含 (in)</Option>
                  <Option value="not_in">不包含 (not_in)</Option>
                  <Option value="gt">大于 (&gt;)</Option>
                  <Option value="lt">小于 (&lt;)</Option>
                  <Option value="gte">大于等于 (&gt;=)</Option>
                  <Option value="lte">小于等于 (&lt;=)</Option>
                  <Option value="contains">包含字符串 (contains)</Option>
                  <Option value="like">模糊匹配 (like)</Option>
                </Select>
              </Form.Item>
            </Col>
            <Col span={8}>
              <Form.Item
                name="type"
                label="条件类型"
                rules={[{ required: true, message: '请选择条件类型' }]}
              >
                <Select placeholder="请选择条件类型">
                  <Option value="user">用户条件</Option>
                  <Option value="resource">资源条件</Option>
                  <Option value="environment">环境条件</Option>
                </Select>
              </Form.Item>
            </Col>
          </Row>

          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                name="value"
                label="条件值"
                tooltip="固定值，与上下文字段二选一"
              >
                <Input placeholder="如: admin, 1, active" />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                name="contextField"
                label="上下文字段"
                tooltip="从上下文获取值的字段，与条件值二选一"
              >
                <Input placeholder="如: user.departmentId, user.id" />
              </Form.Item>
            </Col>
          </Row>

          <Row gutter={16}>
            <Col span={16}>
              <Form.Item
                name="description"
                label="条件描述"
                rules={[{ required: true, message: '请输入条件描述' }]}
              >
                <Input placeholder="如: 只能操作本部门数据" />
              </Form.Item>
            </Col>
            <Col span={8}>
              <Form.Item
                name="status"
                label="状态"
                initialValue={1}
                rules={[{ required: true, message: '请选择状态' }]}
              >
                <Select placeholder="请选择状态">
                  <Option value={1}>启用</Option>
                  <Option value={0}>禁用</Option>
                </Select>
              </Form.Item>
            </Col>
          </Row>

          <Form.Item style={{ marginBottom: 0, textAlign: 'right' }}>
            <Space>
              <Button onClick={() => {
                setConditionModalVisible(false);
                conditionForm.resetFields();
                setEditingCondition(null);
              }}>
                取消
              </Button>
              <Button type="primary" htmlType="submit">
                {editingCondition ? '更新' : '创建'}
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default Permissions;